<template>
  <a-modal v-model:visible="isShow" title="关联权限" :width="'800px'" :body-style="{ width: '800px', height: '550px' }">
    <div>
      <a-transfer
        v-if="isShowTran"
        v-model:target-keys="targetKeys"
        :data-source="mockData"
        :disabled="disabled"
        :show-search="showSearch"
        :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
        :show-select-all="false"
        @change="onChange"
      >
        <template
          #children="{ direction, filteredItems, selectedKeys, disabled: listDisabled, onItemSelectAll, onItemSelect }"
        >
          <div v-if="direction === 'left'" class="role-manag-transfercPermi-page">
            <div style="margin: 5px 10px">
              <a-input-search placeholder="搜索" @search="onSearch"></a-input-search>
            </div>
            <a-tabs v-model:activeKey="tabSwitch.activeKey" @change="tabSwitch.change">
              <a-tab-pane key="1" tab="权限">
                <a-table
                  v-if="tabSwitch.activeKey === '1'"
                  :row-selection="
                    getRowSelection({
                      disabled: listDisabled,
                      selectedKeys,
                      onItemSelectAll,
                      onItemSelect,
                    })
                  "
                  :columns="leftColumns"
                  :data-source="filteredItems"
                  size="small"
                  :style="{ pointerEvents: listDisabled ? 'none' : null }"
                  :custom-row="
                    ({ key, disabled: itemDisabled }) => ({
                      onClick: () => {
                        if (itemDisabled || listDisabled) return
                        onItemSelect(key, !selectedKeys.includes(key))
                      },
                    })
                  "
                  :pagination="paginfoL"
                  :scroll="{ y: 346 }"
                  @change="onChangeTableL"
                />
              </a-tab-pane>
              <a-tab-pane key="2" tab="权限组">
                <a-table
                  v-if="tabSwitch.activeKey === '2'"
                  :row-selection="
                    getRowSelection({
                      disabled: listDisabled,
                      selectedKeys,
                      onItemSelectAll,
                      onItemSelect,
                    })
                  "
                  :columns="groupColumns"
                  :data-source="filteredItems"
                  size="small"
                  :style="{ pointerEvents: listDisabled ? 'none' : null }"
                  :custom-row="
                    ({ key, disabled: itemDisabled }) => ({
                      onClick: () => {
                        if (itemDisabled || listDisabled) return
                        onItemSelect(key, !selectedKeys.includes(key))
                      },
                    })
                  "
                  :pagination="paginfoL"
                  :scroll="{ y: 346 }"
                  @change="onChangeTableL"
                />
              </a-tab-pane>
            </a-tabs>
          </div>
          <a-table
            v-if="direction !== 'left'"
            :row-selection="
              getRowSelection({
                disabled: listDisabled,
                selectedKeys,
                onItemSelectAll,
                onItemSelect,
              })
            "
            :columns="direction === 'left' ? leftColumns : rightColumns"
            :data-source="filteredItems"
            size="small"
            :style="{ pointerEvents: listDisabled ? 'none' : null }"
            :custom-row="
              ({ key, disabled: itemDisabled }) => ({
                onClick: () => {
                  if (itemDisabled || listDisabled) return
                  onItemSelect(key, !selectedKeys.includes(key))
                },
              })
            "
            :pagination="false"
            :scroll="{ y: 346 }"
            @change="onChangeTableR"
          />
        </template>
      </a-transfer>
    </div>
    <template #footer>
      <a-button type="primary" @click="getPerBind">确定</a-button>
      <a-button @click="cancal">取消</a-button>
    </template>
  </a-modal>
</template>
<script>
import { defineComponent, ref, inject, reactive, watch, nextTick } from 'vue'
import factory from '../factory'

export default defineComponent({
  emits: ['closeModal', 'add-success'],
  setup(_, ctx) {
    const { currentItemId } = inject('roleParams')
    //==定义数据===================================
    const mockData = ref([])
    const leftTableColumns = [
      {
        dataIndex: 'name',
        title: '权限名',
      },
      {
        dataIndex: 'key',
        title: '权限标识',
      },
    ]
    const groupTableColumns = [
      {
        dataIndex: 'name',
        title: '权限组名',
      },
      {
        dataIndex: 'key',
        title: '权限组标识',
      },
    ]
    const rightTableColumns = leftTableColumns

    //==穿梭框方法===========================================
    const targetKeys = ref([])
    const disabled = ref(false)
    const showSearch = ref(false)
    const leftColumns = ref(leftTableColumns)
    const rightColumns = ref(rightTableColumns)
    const groupColumns = ref(groupTableColumns)
    let rightSelectKey = []
    const onChange = (nextTargetKeys) => {
      console.log('nextTargetKeys', nextTargetKeys)
      rightSelectKey = nextTargetKeys
      rightPerper = mockData.value.filter((m) => nextTargetKeys.includes(m.key))
    }
    //==人员绑定===
    const getPerBind = () => {
      let post = { privileges: rightSelectKey, role: currentItemId.value.key }
      factory.getPerBind(post).then((res) => {
        ctx.emit('add-success', '')
        cancal()
      })
    }

    const getRowSelection = ({ disabled, selectedKeys, onItemSelectAll, onItemSelect }) => {
      if (onItemSelect.name === 'onLeftItemSelect') {
      } else if (onItemSelect.name === 'onRightItemSelect') {
      }
      return {
        getCheckboxProps: (item) => ({
          disabled: disabled || item.disabled,
        }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows.filter((item) => !item.disabled).map(({ key }) => key)
          onItemSelectAll(treeSelectedKeys, selected)
        },
        onSelect({ key }, selected) {
          onItemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys,
      }
    }

    //==翻页功能======================
    const paginfoL = reactive({ pageNo: 1, pageSize: 10, total: 10, search: '' })
    const onChangeTableL = (pagination) => {
      paginfoL.pageNo = pagination.current
      paginfoL.pageSize = pagination.pageSize
      getPerToBound(paginfoL)
    }
    const onChangeTableR = (pagination, filters, sorter, { currentDataSource }) => {}

    //==显示============================================
    const isShow = ref(false)
    const changeVisible = () => {
      isShow.value = true
    }
    watch(isShow, (nval, oval) => {
      !nval && ctx.emit('closeModal', '')
    })
    const cancal = () => {
      isShow.value = false
    }

    //==得到人员待绑定=============================
    const getPerToBound = (paginfo) => {
      factory.getPerToBound({ ...paginfo, role: currentItemId.value.key }).then((res) => {
        mockData.value = res.data.dataList.map((m) => {
          m.isGroup = false
          m.disabled = false
          return m
        })
        //右边的值一定要保存在 穿梭框的数据中
        rightPerper.forEach((m) => {
          if (!mockData.value.find((itm) => itm.key === m.key)) {
            m.disabled = m.isGroup
            mockData.value.push(m)
          }
        })
      })
    }
    getPerToBound(paginfoL)
    //==得到权限组待绑定=============================
    const getPerGourpToBound = (paginfo) => {
      factory.getPerGourpToBound({ ...paginfo, role: currentItemId.value.key }).then((res) => {
        mockData.value = res.data.dataList.map((m) => {
          m.isGroup = true
          m.disabled = false
          return m
        })
        //右边的值一定要保存在 穿梭框的数据中
        rightPerper.forEach((m) => {
          if (!mockData.value.find((itm) => itm.key === m.key)) {
            m.disabled = !m.isGroup
            mockData.value.push(m)
          }
        })
      })
    }

    //==得到已绑定数据=============================
    let rightPerper = []

    //==权限与权限组切换============================================
    const isShowTran = ref(true)
    const tabSwitch = reactive({
      activeKey: '1',
      change: () => {
        paginfoL.pageNo = 1
        mockData.value = []
        isShowTran.value = false
        nextTick(() => {
          isShowTran.value = true
          if (tabSwitch.activeKey === '1') {
            getPerToBound(paginfoL)
          } else {
            getPerGourpToBound(paginfoL)
          }
        })
      },
    })

    //==搜索===============
    const onSearch = (val) => {
      paginfoL.search = val
      paginfoL.pageNo = 1
      if (tabSwitch.activeKey === '1') {
        getPerToBound(paginfoL)
      } else {
        getPerGourpToBound(paginfoL)
      }
    }

    return {
      mockData,
      targetKeys,
      disabled,
      showSearch,
      leftColumns,
      rightColumns,
      onChange,
      getRowSelection,
      isShow,
      changeVisible,
      onChangeTableL,
      onChangeTableR,
      tabSwitch,
      groupColumns,
      isShowTran,
      getPerBind,
      cancal,
      onSearch,
      paginfoL,
    }
  },
})
</script>
<style lang="less">
.role-manag-transfercPermi-page {
  .ant-tabs-nav-list {
    margin-left: 15px;
  }
}

.role-manag-transfercPermi-page {
  .ant-pagination-options {
    display: none;
  }
}
</style>
